<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/8
 * Time: 14:38
 */

namespace App\Api\Admin\Controllers;


use App\Exceptions\ApiException;
use App\Models\Admin\Log;
use App\Models\Media;
use App\Models\MediaComment;
use App\Models\Report;
use App\Models\User;
use App\Models\Music;
use App\Models\MusicType;
use App\Models\Admin\AdminUser;
use App\Services\OSS;
use App\Services\Sts;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MediaController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        if ($this->user['permissions'] !== '*' && !isset($this->user['permissions']['media'])) {
            throw new ApiException('没有权限', 0);
        }
    }

    /**
     * 视频列表
     * @param Request $request
     * @return array
     */
    public function mediaList(Request $request)
    {
        $title = replace_specialChar($request->input('title'));  // 视频标题
        $name  = replace_specialChar($request->input('name'));   // 用户昵称
        $uid = (int) $request->input('uid'); // 用户id
        $mobie = $request->input('mobile'); // 用户id
        $status = $request->input('status'); // 视频状态 0：审核不通过  1：审核通过  2：待审核
        $status = !isset($status) || !in_array((int) $status, [0, 1, 2]) ? 1 : $status;
        $is_delete = (int) $request->input('is_delete');
        $is_delete = $is_delete ? 1 : 0;
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
      //  $where = [ ['media.status', '=', $status], ['media.is_delete', '=', $is_delete] ];
        $where = [ ['media.is_delete', '=', $is_delete] ];
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.share','media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover','media.is_delete', 'media.video_length', 'users.name as uname','users.mobile'];

        if ($title) {
            $where[] = ['media.title', 'like', '%' . $title . '%'];
        }
        if ($mobie) {
            $where[] = ['users.mobile', 'like', '%' . $mobie . '%'];
        }
        if ($name) {
            $where[] = ['users.name', 'like', '%' . $name . '%'];
        }
        if ($uid) {
            $where[] = ['media.uid', '=', $uid];
        }

        $lists = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->where('media.is_delete',0)->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        $total = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->where('media.is_delete',0)->count();
        $totalPage = ceil($total / $pagesize);
        foreach ($lists as $key=>$value) {
            $lists[$key]['y_media'] = $value['media'];
            $lists[$key]['media'] = getSignUrl($value['media']);
            $lists[$key]['cover'] = getSignUrl($value['cover']);
        }
        unset($list);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
    }
    public function details(Request $request)
    {
        $id  = $request->input('id');
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media','media.tags','media.share', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname'];
        $data = Media::where('media.id','=',$id)->join('users', 'users.id', '=', 'media.uid')->first($fields);
        $arr =explode(",",$data['tags']);
        $data->tags_name = D('tags_name')->whereIn('id',$arr)->get(['id','tags_name']);
        $where_status = [ ['parent_id','<>',0], ['status', 1], ['media_comment.is_delete', 0], ['media_id', $id] ];
        return json_success('ok',$data);
    }
    /**
     * 举报列表
     * @param Request $request
     * @return array
     */
    public function getReport(Request $request)
    {
        $report_type = $request->input('report_type');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $reports_number = $request->input('reports_number');
        if($report_type){
            $where =  ['media_report.status'=>1, 'media_report.report_type'=>$report_type] ;
        }else{
            $where =  ['media_report.status'=>1];
        }
        $fields = ['media_report.id','media.uid', 'media.title', 'media.media','media.cover','media.created_at','media.video_length','media.reports_number','media_report.media_id','media_report.report_type','media_report.content', 'media_report.report_time','media_report.status','users.name', 'users.avatar'];
       // $reports = Report::where($where)->join('media', 'media_report.media_id', '=', 'media.id')->join('users', 'media.uid', '=', 'users.id')->groupBy('media_report.media_id')->skip($offset)->take($pagesize)->orderBy('report_time', 'desc')->get($fields);
        $reports = Media::where($where)->join('media_report','media.id','=','media_report.media_id')->join('users', 'media.uid', '=', 'users.id')->where([ ['media_report.status',1], ['media.status', 1] ])->groupBy('media_report.media_id')->skip($offset)->take($pagesize)->orderBy('report_time', 'desc')->get($fields);
        $total = Media::where($where)->join('media_report','media.id','=','media_report.media_id')->join('users', 'media.uid', '=', 'users.id')->where([ ['media_report.status',1], ['media.status', 1] ])->groupBy('media_report.media_id')->count();
        $totalPage = ceil($total / $pagesize);
        foreach ($reports as &$report){
            $report->media = getSignUrl($report->media);
            $report->cover = getSignUrl($report->cover);
            $report->report_time =D('media_report')->where('media_id',$report->media_id)->max('report_time');
            $report->report_type = D('report_type')->where('id','=',$report->report_type)->value('name');
            $report->reports_number = D('media_report')->where('media_id',$report->media_id)->count();
        }
        //按照举报次数重新排序
        if($reports_number){
            $reports= $reports->toArray();
            foreach ($reports as $key => $row)
            {
                $volume[$key]  = $row['reports_number'];
            }
            if($reports_number=='desc'){
                array_multisort($volume, SORT_DESC, $reports);
            }elseif ($reports_number=='asc'){
                array_multisort($volume, SORT_ASC, $reports);
            }

        }
        unset($report);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage,'list' => $reports]);
    }

    /**
     * @param Request $request
     * 举报详情
     */

    public  function ReportDetails(Request $request){
        $media_id = IT('media_id', true, '请选择视频');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 3;
        $offset = ($page - 1) * $pagesize;
        $media = Media::find($media_id);
        if (!$media) {
            return json_error('视频不存在');
        }
        $fields = ['media_report.id','media.uid', 'media.title', 'media.media','media.cover','media.created_at','media.video_length','media.reports_number','media_report.id','media_report.report_type','media_report.content', 'media_report.report_time','media_report.status'];
        $reports = Report::join('media', 'media_report.media_id', '=', 'media.id')->join('users', 'media.uid', '=', 'users.id')->where([ ['media_id',$media_id ]])->skip($offset)->take($pagesize)->orderBy('report_time', 'desc')->get($fields);
        $total = count($reports);
        $totalPage = ceil($total / $pagesize);
       foreach ($reports as &$report){
          $avatar = Report::join('users', 'media_report.uid', '=', 'users.id')->first(['users.avatar']);
          $report->report_type = D('report_type')->where('id','=',$report->report_type)->value('name');
          $report->name = Report::join('users', 'media_report.uid', '=', 'users.id')->first(['users.name']);
          $report->avatar = getSignUrl($avatar);
          $report->reports_number = D('media_report')->where('media_id',$report->media_id)->count();
      }
        $media_info=[
                'title' => $media->title,
                'player' =>$media->player,
                'staring'=> $media->staring,
                'director' =>$media->director,
                'media' => getSignUrl($media->media),
                'cover' => getSignUrl($media->cover),
                'screenwriter' =>$media->screenwriter,
                'tags' => $media->tags,
                'created_at' => D('media_report')->where('media_id',$media_id)->MAX('report_time'),
                'report_time' =>$media->report_time,
               'reports_number' => Report::where('media_id', $media_id)->count()
        ];
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $reports,'media_info' =>$media_info]);
    }

    /**
     * 举报删除
     *
     */
    public  function DelReport(){
     $id  = IT('id', true, '请输入ID');
     $media_id  = IT('media_id',true,'请输入视频ID');
     //切割多选ID，
  /*   $str_id = explode(",",$id);
     foreach ($str_id as $k){
              $data =  D('media_report')->where('id','=',$k)->delete();
        }*/
        $str_mediaid =explode(",",$media_id);
        foreach ($str_mediaid as $k){
            $data =  Media::where('id','=',$k)->update(['status'=>0]);
        }
     if($data){
           (new Log)->add($this->user, '删除了视频的举报id为-'.$id.'视频id为-'.$media_id);
         return json_success('ok');
     }else{
        return json_error('删除失败');
     }
    }


    /**
     * 视频对应的评论
     * @param Request $request
     * @return array
     */
    public function getComment(Request $request)
    {
        $media_id = IT('media_id', true, '请选择视频');
        $page = max(1, (int) $request->input('page'));
        $content = $request->input('content');
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 3;
        $offset = ($page - 1) * $pagesize;
        $parent_id = (int) $request->input('parent_id');

        $media = Media::find($media_id);

        if (!$media) {
            return json_error('视频不存在');
        }
        if ($content) {
            $where[] = ['content', 'like', '%' . $content . '%'];
        }
        $where_status = [ ['parent_id', $parent_id], ['media_comment.status', 1], ['media_comment.is_delete', 0], ['media_id', $media_id] ];
        $fields = ['media_comment.id', 'content', 'media_comment.created_at', 'users.name', 'users.avatar'];
        if(!empty($content)){
            $comments = MediaComment::where($where)->where($where_status)->join('users', 'media_comment.uid', '=', 'users.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        }else{
            $comments = MediaComment::where($where_status)->join('users', 'media_comment.uid', '=', 'users.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        }
        $total = count($comments);
        $totalPage = ceil($total / $pagesize);

        if ($parent_id === 0) {
            $sub_comments = MediaComment::where([['media_id', $media_id], ['status', 1], ['is_delete', 0]])->get();

            $comment_ids = [];
            foreach ($comments as $comment) {
                $comment_ids[] = $comment->id;
                $comment->sub_comments = 0;
                $comment->avatar = getSignUrl($comment->avatar);
                $comment->Reply_number = D('media_comment')->where('media_id',$media_id)->where('parent_id',$comment->id)->count();
            }
            if (!empty($comment_ids)) {
                foreach ($sub_comments as $comment) {
                    if ($index = array_search($comment->parent_id, $comment_ids)) {
                        $comments[$index]->sub_comments += 1;
                    }
                }
            }
        }

        return json_success('ok', ['totalpage' => $totalPage,'total'=>$total, 'list' => $comments,]);
    }

    /**
     * 删除评论
     * @return array
     */
    public function deleteComment()
    {
        $comment_id = IT('comment_id', true, '请选择要删除的评论');

        $comment = MediaComment::find($comment_id);
        if (!$comment || $comment->is_delete == '1' || $comment->status != '1') {
            return json_error('评论不存在');
        }

        DB::beginTransaction();
        $res = true;
        $comment->is_delete = 1;
        $res = $res && false !== $comment->save();
        $res = $res && false !== DB::table('media')->where('id', $comment->media_id)->decrement('comments', 1);

        if (!$res) {
            DB::roolback();
            return json_error('删除评论失败，稍后再试');
        }

        DB::commit();
        (new Log)->add($this->user, '删除了一条评论，评论id为“'.$comment_id.'”');
        return json_success('ok');
    }

    /**
     * 审核视频
     * @param Request $request
     * @return array
     */
    public function changeStatus(Request $request)
    {
        $media_id = IT('media_id', true, '请选择视频');
        $status = IT('status', true, '请选择状态');

        $reason = $request->input('reason');
        $reason = $reason ?: '';

        if (!in_array($status, ['1', '2'])) {
            return json_error('审核状态有误');
        }

        $media = Media::find($media_id);
        $is_read = $status === '2' ? 0 : 1;

        if (!$media || $media['is_delete'] == '1') {
            return json_error('审核影片不存在');
        }

        if ($status === '2' && !$reason) {
            return json_error('请填写审核失败原因');
        }

        DB::beginTransaction();
        $res = true;
        $media->status = $status;
        $res = $res && false !== $media->save();

        $res = $res && DB::table('media_verify')->insert(['media_id' => $media_id, 'uid' => $media->uid, 'status' => $status, 'reason' => $reason, 'admin_uid' => $this->user['id'], 'create_at' => date('Y-m-d H:i:s'), 'is_read' => $is_read]);

        if (!$res) {
            DB::rollback();
            return json_error('审核失败，请稍后再试');
        }

        DB::commit();
        (new Log)->add($this->user, '审核视频，视频id为' . $media_id . ', 标题为“'. $media->title .'”');
        return json_success('ok');
    }

    /**
     * @param Request $request
     * 待审核视频列表
     * @return array
     */
    public function  checkupList(Request $request){
        $title = $request->input('title');  // 视频标题
        $name  = $request->input('name');   // 用户昵称
        $uid = (int) $request->input('uid'); // 用户id
        $is_delete = (int) $request->input('is_delete');
        $is_delete = $is_delete ? 1 : 0;
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $where = [ ['media.status', '=', 2], ['media.is_delete', '=', $is_delete] ];
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname'];
        if ($title) {
            $where[] = ['media.title', 'like', '%' . $title . '%'];
        }
        if ($name) {
            $where[] = ['users.name', 'like', '%' . $name . '%'];
        }
        if ($uid) {
            $where[] = ['media.uid', '=', $uid];
        }
        $lists = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        $total = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->count();
        $totalPage = ceil($total / $pagesize);
        // 获取内网视频图片链接
        $datetime = new DateTime();
        $datetime->modify('+1 day');
        foreach ($lists as &$list) {
            $list->media = getSignUrl($list->media);
            $list->cover = getSignUrl($list->cover);
        }
        unset($list);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
    }

    /**
     * @return array
     * 审核不通过的原因列表
     */
    public function AuditReasons(){
      //  $data= config('admin.report_status');
        $data =D('report_type')->get(['id','name']);
        return json_success('ok',$data);
    }
    /**
     * @param Request $request
     * 审核不通过
     * @return array
     */
    public function NotThrough(Request $request){
        $title = $request->input('title');  // 视频标题
        $name  = $request->input('name');   // 用户昵称
        $uid = (int) $request->input('uid'); // 用户id
        $is_delete = (int) $request->input('is_delete');
        $is_delete = $is_delete ? 1 : 0;
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $where = [ ['media.status', '=', 0], ['media.is_delete', '=', $is_delete] ];
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname','media_verify.reason'];
        if ($title) {
            $where[] = ['media.title', 'like', '%' . $title . '%'];
        }
        if ($name) {
            $where[] = ['users.name', 'like', '%' . $name . '%'];
        }
        if ($uid) {
            $where[] = ['media.uid', '=', $uid];
        }
        $lists = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->join('media_verify', 'media_verify.media_id', '=', 'media.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        $total = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->join('media_verify', 'media_verify.media_id', '=', 'media.id')->count();
        $totalPage = ceil($total / $pagesize);
        // 获取内网视频图片链接
        $datetime = new DateTime();
        $datetime->modify('+1 day');
        foreach ($lists as &$list) {
            $list->media = getSignUrl($list->media);
            $list->cover = getSignUrl($list->cover);
        }
        unset($list);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
    }
    public function mediaUpload(Request $request)
    {

        $cover_file = IT('cover', true, '请上传封面');
        $media = IT('media',true, '请上传视频');
        $tags= IT('tags',true,'请选择影片分类');
        $uid = IT('uid', true, '请选择用户');
        $title = IT('title', true, '请填写视频标题');
        $video_length = IT('video_length', true, '请填写视频时长');
        $screenwriter = IT('screenwriter');
        $staring = IT('staring');
        $director = IT('director');

        $user = User::find($uid);
        if (!$user || $user->status != '1') {
            return json_error('用户不存在');
        }
        /*  $ext = check_video();
         if (empty($ext)) {
             return json_error('上传类型不支持');
         }
         if (filesize($request->file('video_file')) > 5*pow(1024,3)) {
             return json_error('上传文件不能超过5GB');
         }
      /*     $content_type = get_content_type($ext);

            $name = substr(md5($uid), 0, 4) . '/' . date('Ym') . '/' . date('Ymd') . md5(uniqid()) . '.' . $ext;

    //        $name = 'videos/'.date('Y-m-d').'/'.date('YmdHis').uniqid().$ext;
       /*     $config = config('basic.oss');
            $res = OSS::publicUpload($config['bucket'],$name,$request->file('video_file'),$content_type);

            if ($res) {
                $video_url = $config['video_url'] . '/' . $name;*/

        if ($screenwriter) {
            $screenwriter = json_encode(explode(',', trim($screenwriter, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($screenwriter)) {
                return json_error('编剧格式错误');
            }
        }
        if ($staring) {
            $staring = json_encode(explode(',', trim($staring, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($staring)) {
                return json_error('编剧格式错误');
            }
        }
        if ($director) {
            $director = json_encode(explode(',', trim($director, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($director)) {
                return json_error('编剧格式错误');
            }
        }
   /*     if($tags){
            $tags = json_encode(explode(',', trim($tags, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($tags)) {
                return json_error('栏目格式错误');
            }
        }*/
        $data = [
            'uid' => $uid,
            'title' => $title,
            'media' => clear_urlcan($media),
            'screenwriter' => $screenwriter,
            'staring' => $staring,
            'director' => $director,
            'video_length' => $video_length,
            'cover' => clear_urlcan($cover_file),
            'date' => date('Y-m-d'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'tags' => $tags
        ];
            $media_data = Media::insertGetId($data);
       /* }*/
        if($media_data){
            (new Log)->add($this->user, '上传了视频' . ', 视频ID为' . $media_data .'-名称为 '.$title. '');
            return json_success('ok');
        }else{
            return json_error('上传失败');
        }
    }
    /**
     * 获取网页上传OSS签名
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function getWapUploadToken(Request $request)
    {
        //$img_url = IT('img_url');
        $userTicket = AdminUser::where('id','=', $this->user['id'])->first();
        if ($userTicket) {
            $uid = $userTicket->id;
        } else {
            throw new ApiException('参数有误', 0);
        }
        $id = env('WEB_ACCESS_ID');
        $key = env('WEB_ACCESS_KEY');
        $host = 'http://'.env('WEB_BUCKET_NAME').'.'.env('WEB_ENDPOINT');

        $now = time();
        $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);

        $dir = substr(md5($uid), 0, 4) . '/' . date('Ym') . '/';

        //最大文件大小.用户可以自己设置
        $condition = ['content-length-range', 0, 104857600];
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = ['starts-with', '$key', $dir];
        $conditions[] = $start;
        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
        $response = array();
        //  $Resources_type =strtolower(pathinfo($img_url, PATHINFO_EXTENSION));
        $response['filename'] = date('Ymd') . md5(uniqid());
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;

        return json_success('ok', $response);
    }

    private function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }
    /**
     * 解析媒体域名
     * @param string $mediaUrl
     * @return array
     */
    private function parseUrl($mediaUrl = '')
    {
        $data = parse_url($mediaUrl);

        return ['bucketName' => substr($data['host'], 0, strpos($data['host'], '.')), 'ossKey' => substr($data['path'], 1)];
    }
    public function ConfirmUpload(){
        $img_file = IT('img_file', true, '请上传封面');
        if (!strpos($img_file, 'oss-cn-shenzhen.aliyuncs.com')) {
            return json_error('参数有误');
        }
        $img_file = getSignUrl($img_file);
        $return = array(
            'img_url' => $img_file
        );
       return json_success('上传成功', $return);
    }
    public function VideoUpload(Request $request){
      $video_file = IT('video_file', true, '请上传视频');
        if (!strpos($video_file, 'oss-cn-shenzhen.aliyuncs.com')) {
            return json_error('参数有误');
        }
        $video_file = getSignUrl($video_file);
        $return = array(
            'video_url' => $video_file
        );
        return json_success('上传成功', $return);
    }
    /**
     * @return array
     * 视频删除
     */
    public function DelMedia(){
        $media_id = IT('media_id',true,'请输入视频ID');
        $str = explode(",",$media_id);
        foreach ($str as $k){
            $list = Media::whereIn('id',$str)->update(['is_delete'=>1]);
            $Comment = MediaComment::where('media_id',$str)->first();
            MediaComment::where('media_id',$str)->whereOr('parent_id',$Comment->id)->update(['is_delete'=>1]);
        }
        if($list!==false) {
            (new Log)->add($this->user, '删除了视频id为-'.$media_id);
            return json_success("ok");
        }else{
            return json_error('删除失败！');
        }
    }
    /**
     * @return array
     * 视频启用禁用
     */
    public function MediaEnable()
    {
        $media_id = IT('media_id',true,'请输入视频ID');
        $status = IT('status',true,'请输入状态');
        $list = Media::where('id',$media_id)->update(['status'=>$status]);
        if($list!==false) {
            (new Log)->add($this->user, '修改视频状态为-'.$status);
            return json_success("ok");
        }else{
            return json_error('启用失败！');
        }
    }
    /**
     * 音乐列表
     * @param Request $request
     * @return array
     */
    public function MusicList(Request $request){
        $category = $request->input('category');
        $page = intval($request->input('page')) ?: 1;
        $page = $page - 1;
        $pageSize =  intval($request->input('pageSize')) ?: 15;
        $name = $request->input('name');
        $where = [];
        if ($name) {
            $where[] = ['music_name', 'like', '%' . $name . '%'];
        }
        //有音乐类别选择
        if(!empty($category) || $category == '0'){
            $total = Music::where($where)->where('category','=',$category)->where('is_delete','=',0)->count();
            $totalPage = ceil($total / $pageSize);
            $music_data =Music::where('category','=',$category)->where($where)->where('is_delete','=',0)->skip($page * $pageSize)->take($pageSize)->orderBy('sort','asc')->orderBy('number','desc')->get(['id','music_name','music_link','category','time_length','created_at','sort','status','number']);
        }else{
            //无音乐类别选择
            $total = Music::where($where)->where('is_delete','=',0)->count();
            $totalPage = ceil($total / $pageSize);
            $music_data =Music::where($where)->skip($page * $pageSize)->where('is_delete','=',0)->take($pageSize)->orderBy('sort','asc')->orderBy('number','desc')->get(['id','music_name','music_link','category','time_length','created_at','sort','status','number']);
        }

        foreach ($music_data as &$list) {
            $list->music_link = getSignUrl($list->music_link);
            $list->category = D('music_type')->where('id','=',$list->category)->value('name');
        }
        unset($list);
        return json_success("ok",['total'=>$total,'totalPage' => $totalPage, 'list' => $music_data]);
    }

    /**
     * 音乐类别
     * @return array
     */
    public function MusicType(){
        $type_data = MusicType::where(['status'=>0,'enable'=>1])->get(['id','name']);
        return json_success("ok",$type_data);

    }

    /**
     * 音乐上传
     * @return array
     *
     */
    public function MusicUpload(){
       $music_name= IT('music_name', true,'请填写音乐名称');
       $music_link= IT('music_link',true, '请填写音乐链接地址');
       $category= IT('category',true, '请选择音乐分类');
       $time_length= IT('time_length',true, '请填写音乐时长');
       $data =[
           'music_name' => $music_name,
           'music_link' => clear_urlcan($music_link),
           'category'   => $category,
           'created_at'   => time2date(),
           'time_length' => $time_length,
       ];
        $music_data = Music::insertGetId($data);
        if($music_data){
            (new Log)->add($this->user, '上传了音乐' . ', 音乐名称为-'.$music_name);
            //查找当前分类的最大排序数
            $max = Music::where('category','=',$category)->where('is_delete','=',0)->max('sort');
            $increase=$max+1;
            //将自增的排序数字更新到上传的歌曲排序中
            Music::where('id','=',$music_data)->update(['sort'=>$increase]);
            return json_success('ok');
        }else{
            return json_error('上传失败');
        }
    }

    /**
     * 音乐启用
     * @return array
     */
    public function Enable(){
        $id = trim(IT('id', true,'请输入音乐id'));
        $status = trim(IT('status',true,'请输入你要改变的状态'));
        if($status ==1){
           $update= Music::where('id','=',$id)->first();
           $update_date= $update->update(['status'=>1]);
           if($update_date){
               //查找当前分类的最大排序数
               $max = Music::where('category','=',$update->category)->where('is_delete','=',0)->max('sort');
               if($update->sort === $max ){
                   $increase=$max;
               }else{
                   $increase=$max+1;
               }
               //将音乐不不启用的状态改为，当前类别最大的值
               Music::where('id','=',$id)->update(['sort'=>$increase]);
               (new Log)->add($this->user, '修改了音乐-'.$update['music_name'].'状态为-不启用');
               return json_success('ok');
           }
        }elseif ($status ==0){
            $update= Music::where('id','=',$id)->first();
            $update_date= $update->update(['status'=>0]);
            if($update_date){
                (new Log)->add($this->user, '修改了音乐-'.$update_date['music_name'].'状态为-启用');
                return json_success('ok');
            }
        }
    }

    /**
     * 音乐删除
     * @return array
     */
    public function DelMusic(){
        $id = IT('id',true,'请输入音乐id');
        $music = Music::where('id','=',$id)->first();
        $del_data = Music::where('id','=',$id)->update(['is_delete'=>1]);
        if($del_data){
            (new Log)->add($this->user, '删除了音乐-'.$music->music_name);
             return json_success('ok');
        }else{
             return json_error('删除失败');
        }
    }
    /**
     * 音乐排序修改
     * @return array
     */
    public function UpdateSort(){
        $id = IT('id', true,'请输入音乐ID');
        $sort = IT('sort',true,'请输入要改变的数字');
        $row = Music::where('id','=',$id)->first();
        if($row->sort == $sort)
            return json_success('ok');

        // 排序
        $type = 1;
        $min = $sort;
        $max = $row->sort-1;
        if($sort > $row->sort){
            $type = 2;
            $min = ($row->sort+1);
            $max = $sort;
        }

        $list = Music::where([['id', '!=', $id], ['sort', '>=', $min], ['sort', '<=', $max]])->orderby('sort', 'asc')->get();
        if(!empty($list)){
            $model = new Music();
            foreach ($list->toArray() as $key=>$value){
                $sql = "update ".$model->getTable()." set sort=".($sort+$key+1)." where id=".$value['id'] ." AND category=".$value['category'] ;
                if($type == 2)
                    $sql = "update ".$model->getTable()." set sort=".($min+$key-1)." where id=".$value['id'] ." AND category=".$value['category'] ;
                $update = DB::update($sql);
            }
        }
        $update = Music::where('id', $id)->update(['sort'=>$sort]);
        if($update)
            (new Log)->add($this->user, '修改了音乐排序，修改后的排序数为-'.$sort);
        return json_success('ok');
        return json_error('修改失败');
    }
    /**
     *音乐分类的添加
     *
     */
    public function AddMusicType(){
        $name = IT('name',true,'请输入名称');
        $check_name=MusicType::where('name','=',$name)->first();
        if($check_name){
           EE('改名称已存在');
         }
        $insert_data= MusicType::insert(['name'=>$name,'created_at'=>time2date()]);
        if($insert_data){
            (new Log)->add($this->user, '添加了音乐分类名称为-'.$name);
            return json_success('ok');
        }else{
            return json_error('添加失败');
        }
    }

    /**
     * @return array
     * 音乐分类删除
     */
    public function DelMusicType(){
        $name = IT('name',true,'请输入id');
        $check_name=MusicType::where('name','=',$name)->first();
        if(!$check_name){
            EE('改类别不存在');
        }
        $insert_data= MusicType::where('name','=',$name)->update(['status'=>1]);
        if($insert_data){
            (new Log)->add($this->user, '删除了音乐分类名称为-'.$check_name->name);
            return json_success('ok');
        }else{
            return json_error('删除失败');
        }

    }

    /**
     * 音乐分类启,禁用
     */

    public function MusicTypeEnable(){
        $id= IT('id',true,'请输入音乐类型ID');
        $enable = IT('enable',true,'请输入启用，禁用数');
        $data = MusicType::where('id','=',$id)->update(['enable'=>$enable]);
        if($data){
            return json_success('ok');
        }else{
            return json_error('修改失败');
        }

    }

    /**
     * @return array
     * 音乐分类详情
     */
    public function MusicDetails()
    {
        $id= IT('id',true,'请输入音乐类型ID');
        $data =MusicType::where('id','=',$id)->first(['id','name','sort']);
        return json_success('ok',$data);
    }
    /**
     *音乐分类排序修改
     *
     */
    public function MusicSorting(){
      $id= IT('id',true,'请输入音乐类型ID');
      $name= IT('name');
      $sort = IT('sort');
      $check_Music = MusicType::where('id','=',$id)->first();
      if(!$check_Music){
          return json_error('没有该类别');
      }
      if(isset($name)){
          $update = MusicType::where('id','=',$id)->update(['name'=>$name]);
      }
      if(isset($sort)){
          MusicType::where('sort','>=',$sort)->increment('sort');
          $update = MusicType::where('id','=',$id)->update(['sort'=>$sort]);
      }
      if($update){
          (new Log)->add($this->user, '修改了音乐类别,名称为-'.$check_Music->name);
          return json_success('ok');
      }else{
          return json_error('修改失败');
      }
    }







}